<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 分类数-->
      <el-col :lg="4" :xs="24">
        <el-card shadow="hover">
          <el-input v-model="categorySearchName" clearable placeholder="请输入分类名称" prefix-icon="Search" />
          <el-tree
            ref="categoryTreeRef"
            :data="categoryOptions"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :props="{ label: 'label', children: 'children' }"
            class="mt-2"
            default-expand-all
            highlight-current
            node-key="id"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="auto">
                <el-form-item label="属性名" prop="attrName">
                  <el-input v-model="queryParams.attrName" clearable placeholder="请输入属性名" @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="是否需要检索" prop="searchType">
                  <el-select v-model="queryParams.searchType" clearable placeholder="请选择是否需要检索">
                    <el-option v-for="dict in gulimall_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="值类型" prop="valueType">
                  <el-select v-model="queryParams.valueType" clearable placeholder="请选择值类型">
                    <el-option v-for="dict in pms_attr_value_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="属性图标" prop="icon">
                  <el-input v-model="queryParams.icon" clearable placeholder="请输入属性图标" @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="可选值列表" prop="valueSelect">
                  <el-input v-model="queryParams.valueSelect" clearable placeholder="请输入可选值列表" @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="属性类型" prop="attrType">
                  <el-select v-model="queryParams.attrType" clearable placeholder="请选择属性类型">
                    <el-option v-for="dict in pms_attr_attr_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="启用状态" prop="enable">
                  <el-select v-model="queryParams.enable" clearable placeholder="请选择启用状态">
                    <el-option v-for="dict in gulimall_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="快速展示" prop="showDesc">
                  <el-select v-model="queryParams.showDesc" clearable placeholder="请选择快速展示">
                    <el-option v-for="dict in gulimall_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['pms:attr:add']" icon="Plus" plain type="primary" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['pms:attr:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['pms:attr:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
                  >删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['pms:attr:export']" icon="Download" plain type="warning" @click="handleExport">导出</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="attrList" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column v-if="true" align="center" label="属性id" prop="attrId" />
            <el-table-column align="center" label="属性名" prop="attrName" />
            <el-table-column align="center" label="是否需要检索" prop="searchType">
              <template #default="scope">
                <dict-tag :options="gulimall_yes_no" :value="scope.row.searchType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="值类型" prop="valueType">
              <template #default="scope">
                <dict-tag :options="pms_attr_value_type" :value="scope.row.valueType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="属性图标" prop="icon" />
            <el-table-column align="center" label="可选值列表" prop="valueSelect" />
            <el-table-column align="center" label="属性类型" prop="attrType">
              <template #default="scope">
                <dict-tag :options="pms_attr_attr_type" :value="scope.row.attrType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="启用状态" prop="enable">
              <template #default="scope">
                <dict-tag :options="gulimall_yes_no" :value="scope.row.enable ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="所属分类" prop="catelogId" />
            <el-table-column align="center" label="快速展示" prop="showDesc">
              <template #default="scope">
                <dict-tag :options="gulimall_yes_no" :value="scope.row.showDesc ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['pms:attr:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['pms:attr:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNum"
            :total="total"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改商品属性对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="attrFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="分类" prop="catelogId">
          <el-tree-select
            v-model="form.catelogId"
            :data="categoryOptions"
            :props="{ value: 'id', label: 'label', children: 'children', disabled: 'disabled' }"
            check-strictly
            placeholder="请选择父分类编码"
            value-key="catId"
          />
        </el-form-item>
        <el-form-item label="属性类型" prop="attrType">
          <el-select v-model="form.attrType" placeholder="请选择属性类型">
            <el-option v-for="dict in pms_attr_attr_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性名" prop="attrName">
          <el-input v-model="form.attrName" placeholder="请输入属性名" />
        </el-form-item>

        <el-form-item label="值类型" prop="valueType">
          <el-select v-model="form.valueType" placeholder="请选择值类型">
            <el-option v-for="dict in pms_attr_value_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入属性图标" />
        </el-form-item>
        <el-form-item label="可选值列表" prop="valueSelect">
          <el-input v-model="form.valueSelect" placeholder="请输入可选值列表[多个用逗号分隔]" />
        </el-form-item>
        <el-form-item label="是否需要检索" prop="searchType">
          <el-radio-group v-model="form.searchType">
            <el-radio v-for="dict in gulimall_yes_no" :key="dict.value" :value="dict.value === '1'">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快速展示" prop="showDesc">
          <el-radio-group v-model="form.showDesc">
            <el-radio v-for="dict in gulimall_yes_no" :key="dict.value" :value="dict.value === '1'">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用状态" prop="enable">
          <el-radio-group v-model="form.enable">
            <el-radio v-for="dict in gulimall_yes_no" :key="dict.value" :value="dict.value === '1'">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Attr" lang="ts">
import { addAttr, delAttr, getAttr, listAttr, updateAttr } from '@/api/pms/attr';
import { AttrForm, AttrQuery, AttrVO } from '@/api/pms/attr/types';
import { listCategory, tree } from '@/api/pms/category';
import { Tree } from '@/api/common/types';
import { ElTree } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pms_attr_value_type, pms_attr_attr_type, gulimall_yes_no } = toRefs<any>(
  proxy?.useDict('pms_attr_value_type', 'pms_attr_attr_type', 'gulimall_yes_no')
);

const attrList = ref<AttrVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const attrFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AttrForm = {
  attrId: undefined,
  attrName: undefined,
  searchType: true,
  valueType: 0,
  icon: undefined,
  valueSelect: undefined,
  attrType: 1,
  enable: true,
  catelogId: undefined,
  showDesc: true
};
const data = reactive<PageData<AttrForm, AttrQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    attrName: undefined,
    searchType: undefined,
    valueType: undefined,
    icon: undefined,
    valueSelect: undefined,
    attrType: undefined,
    enable: undefined,
    catelogId: undefined,
    showDesc: undefined,
    params: {}
  },
  rules: {
    attrId: [{ required: true, message: '属性id不能为空', trigger: 'blur' }],
    attrName: [{ required: true, message: '属性名不能为空', trigger: 'blur' }],
    searchType: [{ required: true, message: '是否需要检索不能为空', trigger: 'change' }],
    valueType: [{ required: true, message: '值类型不能为空', trigger: 'change' }],
    // icon: [{ required: true, message: '属性图标不能为空', trigger: 'blur' }],
    valueSelect: [{ required: true, message: '可选值列表不能为空', trigger: 'blur' }],
    attrType: [{ required: true, message: '属性类型不能为空', trigger: 'change' }],
    enable: [{ required: true, message: '启用状态不能为空', trigger: 'change' }],
    catelogId: [{ required: true, message: '所属分类不能为空', trigger: 'change' }],
    showDesc: [{ required: true, message: '快速展示不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品属性列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAttr(queryParams.value);
  attrList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  attrFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AttrVO[]) => {
  ids.value = selection.map((item) => item.attrId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.catelogId = queryParams.value.catelogId;
  dialog.visible = true;
  dialog.title = '添加商品属性';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AttrVO) => {
  reset();
  const _attrId = row?.attrId || ids.value[0];
  const res = await getAttr(_attrId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改商品属性';
};

/** 提交按钮 */
const submitForm = () => {
  attrFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.attrId) {
        await updateAttr(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAttr(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AttrVO) => {
  const _attrIds = row?.attrId || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品属性编号为"' + _attrIds + '"的数据项？').finally(() => (loading.value = false));
  await delAttr(_attrIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'pms/attr/export',
    {
      ...queryParams.value
    },
    `attr_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  handleNodeTree();
});

const categorySearchName = ref('');
const categoryOptions = ref<Tree[]>([]);

/**
 * 获取分类树
 */
const handleNodeTree = async () => {
  let res = await tree({});
  categoryOptions.value = res.data;
};

// 监控 搜索框 调用过滤方法
const categoryTreeRef = ref<InstanceType<typeof ElTree>>();
watch(categorySearchName, (val) => {
  categoryTreeRef.value!.filter(val);
});
/**
 * 搜索节点
 * @param value 搜索值
 * @param data  节点数据
 */
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  console.log('filterNode', value, data);
  return data.label.includes(value);
};
/** 节点单击事件 */
const handleNodeClick = (data: Tree) => {
  queryParams.value.catelogId = data.id;
  handleQuery();
};

type CategoryOption = {
  catId: number;
  name: string;
  children?: CategoryOption[];
};

const categoryOptionsSelect = ref<CategoryOption[]>([]);
/** 查询商品三级分类下拉树结构 */
const getTreeselect = async () => {
  const res = await listCategory();
  categoryOptionsSelect.value = [];
  const data: CategoryOption = { catId: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<CategoryOption>(res.data, 'catId', 'parentCid');
  categoryOptionsSelect.value.push(data);
};
</script>
